<?php

namespace simpleHandle\Component\UtilProcess;

use Swoole\Process as swooleProcess;
use Exception;

class Process
{
	private array  $pidArr;
	private string $pidfile;
	private string $namespace;
    private array $disabledCoroutineList = [];

    public function SetDisabledCoroutineList(string $processName): Process
    {
        $this->disabledCoroutineList[] = $processName;
        return $this;
    }

    /**
     * @param array $processArr // 进程名一维数组
     * @param string $ROOT // 根目录
     * @param string $namespace
     * @throws Exception
     */
	public function Start( array $processArr, string $ROOT = "/", string $namespace = "Process\\" ) {
		$path            = $ROOT;
		$this->pidfile   = $path . DIRECTORY_SEPARATOR . 'pid.pid';
		$this->namespace = $namespace;
		printf( "\033[34m%-20s%-20s\033[0m\n", "PHP_VERSION", phpversion() );
		printf( "\033[34m%-20s%-20s\033[0m\n", "SWOOLE_VERSION", swoole_version() );
		foreach ( $processArr as $v ) {
			$this->CreateProcess( $v );
		}
		file_put_contents( $this->pidfile, json_encode( $this->pidArr, JSON_PRETTY_PRINT ) );
		printf( "\033[32m%-20s\033[0m\n", "SERVER START SUCCESS" );
	}

	/**
	 * @param string $process_name
	 * @throws Exception
	 */
	private function CreateProcess( string $process_name ) {
		try {
			$className = $this->namespace . $process_name;
			$process   = new swooleProcess( function () use ( $className ) {
				( new $className )->run();
			} );
            $isEnableCoroutine = !in_array($process_name,$this->disabledCoroutineList);
			$process->set( [
				'enable_coroutine' => $isEnableCoroutine,
				'name'             => $process_name
			] );
			$process->start();
			printf( "\033[32m%-20s%-20s\033[0m\n", "[PID] " . $process->pid, "[PROCESS_NAME] " . $process_name );
			file_put_contents( $this->pidfile, json_encode( $this->pidArr, JSON_PRETTY_PRINT ) );
		} catch ( \Throwable $th ) {
			throw new Exception( $th->getMessage() );
		}
	}
}